package com.example.goodpet.db;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import androidx.room.Room;

import com.example.goodpet.db.dao.GoodpetHistoryDAO;
import com.example.goodpet.db.dao.TieziHistoryDAO;
import com.example.goodpet.db.dao.SearchHistoryDAO;
import com.example.goodpet.db.dao.UserDAO;

public class DatabaseHelper {
    private final String TAG=this.getClass().getSimpleName();
    private static DatabaseHelper instance;
    private AppDatabase mDatabase;
    private Context mContext;


    private DatabaseHelper(Context context){
        this.mContext = context.getApplicationContext();}

    public static DatabaseHelper getInstance(Context context) {
        if(instance == null) {
            synchronized (DatabaseHelper.class) {
                if(instance == null) {
                    instance = new DatabaseHelper(context);
                }
            }
        }
        return instance;
    }

    public void initDb() {

        // 以下数据库升级设置，为升级数据库将清掉之前的数据，如果要保留数据，慎重采用此种方式
        // 可以采用addMigrations()的方式，进行数据库的升级
        String dbName = "app_database";
        mDatabase = Room.databaseBuilder(mContext, AppDatabase.class, dbName)
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration()
                .build();
    }

    public void closeDb() {
        if(mDatabase != null) {
            mDatabase.close();
            mDatabase = null;
        }
    }

    public UserDAO getUserDAO(){
            if(mDatabase != null) {
                return mDatabase.userDao();
            }
            Log.e(TAG, "get userDao failed, should init db first");
            return null;
    }
    public GoodpetHistoryDAO getGoodpetHistoryDAO(){
        if(mDatabase != null) {
            return mDatabase.goodpetHistoryDAO();
        }
        Log.e(TAG, "get GoodpetHistory failed, should init db first");
        return null;
    }
    public TieziHistoryDAO getTieziHistoryDAO(){
        if(mDatabase != null) {
            return mDatabase.tieziHistoryDAO();
        }
        Log.e(TAG, "get TieziHistory failed, should init db first");
        return null;
    }

    public SearchHistoryDAO getSearchHistoryDAO(){
        if(mDatabase != null) {
            return mDatabase.searchHistoryDAO();
        }
        Log.e(TAG, "get SearchHistory failed, should init db first");
        return null;
    }

}
